/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mongodb.repository.handler;

import java.util.Iterator;
import java.util.Map;

import org.springframework.util.Assert;

import com.mongodb.Mongo;

/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-3-7
 *
 */
public class SimpleAssignMongodbHandler implements AssignMongodbHandler {

	private Map<String, Mongo> mongoMap;
	
	/**
	 * @param mongoMap
	 */
	public SimpleAssignMongodbHandler(Map<String, Mongo> mongoMap) {
		this.mongoMap = mongoMap;
	}

	/* (non-Javadoc)
	 * @see com.foreveross.persistent.mongodb.Handler.AssignMongodbHandler#assignMongo()
	 */
	@Override
	public Mongo assignMongo() {
		Assert.notNull(mongoMap, "mongoMap must not be null");
		
		Mongo mongo, cur = null;
		int i = 999999999, c;
		for (Iterator iterator = mongoMap.keySet().iterator(); iterator.hasNext();) {
			String type = (String) iterator.next();
			mongo = mongoMap.get(type);
			c = mongo.getDatabaseNames().size();
			if(c < i){
				i = c;
				cur = mongo;
			}
			
		}
		return cur;
	}

}
